using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Work.API.Applications.Read.Commands;
using Work.API.Dtos.DrugManagement;
using Work.Domain;
using Work.Domain.DrugManage;
using Work.ErrorCode;
using Work.Infrastructure.Interfaces;

namespace Work.API.Applications.Read.CommandHandlers
{
    /// <summary>
    /// 获取未打单处方明细处理器（用于查看检药单模块 - 未打单列表）
    /// 查询已支付但未创建检药单的处方明细
    /// </summary>
    public class GetUnbilledPrescriptionsQueryHandler : IRequestHandler<GetUnbilledPrescriptionsQuery, ApiResult<List<UnbilledPrescriptionDto>>>
    {
        private readonly IBaseRepository<Domain.PrescriptionItem> _prescriptionItemRepo;
        private readonly IBaseRepository<DrugInspection> _inspectionRepo;
        private readonly IBaseRepository<Drug> _drugRepo;
        private readonly IMapper _mapper;

        public GetUnbilledPrescriptionsQueryHandler(
            IBaseRepository<Domain.PrescriptionItem> prescriptionItemRepo,
            IBaseRepository<DrugInspection> inspectionRepo,
            IBaseRepository<Drug> drugRepo,
            IMapper mapper)
        {
            _prescriptionItemRepo = prescriptionItemRepo;
            _inspectionRepo = inspectionRepo;
            _drugRepo = drugRepo;
            _mapper = mapper;
        }

        public async Task<ApiResult<List<UnbilledPrescriptionDto>>> Handle(GetUnbilledPrescriptionsQuery request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<List<UnbilledPrescriptionDto>>();

            try
            {
                // 1. 获取所有已支付的处方明细
                var query = _prescriptionItemRepo.GetAll()
                    .Include(pi => pi.Patient)
                    .Include(pi => pi.Appointment)
                    .Where(pi => pi.PaymentStatus == "已支付")
                    .AsNoTracking();

                // 2. 获取所有已创建检药单的处方明细ID
                var billedPrescriptionItemIds = await _inspectionRepo.GetAll()
                    .Select(di => di.PrescriptionItemId)
                    .ToListAsync(cancellationToken);

                // 3. 排除已创建检药单的处方明细
                query = query.Where(pi => !billedPrescriptionItemIds.Contains(pi.PrescriptionItemId));

                // 处理时间筛选类型（今天/本周/本月/今年/全部）
                DateTime? startDate = request.StartDate;
                DateTime? endDate = request.EndDate;

                if (!string.IsNullOrWhiteSpace(request.TimeFilterType))
                {
                    var now = DateTime.Now;
                    switch (request.TimeFilterType)
                    {
                        case "今天":
                            startDate = now.Date;
                            endDate = now.Date.AddDays(1).AddSeconds(-1);
                            break;
                        case "本周":
                            var dayOfWeek = (int)now.DayOfWeek;
                            dayOfWeek = dayOfWeek == 0 ? 7 : dayOfWeek; // 周日转为7
                            startDate = now.Date.AddDays(1 - dayOfWeek);
                            endDate = startDate.Value.AddDays(7).AddSeconds(-1);
                            break;
                        case "本月":
                            startDate = new DateTime(now.Year, now.Month, 1);
                            endDate = startDate.Value.AddMonths(1).AddSeconds(-1);
                            break;
                        case "今年":
                            startDate = new DateTime(now.Year, 1, 1);
                            endDate = startDate.Value.AddYears(1).AddSeconds(-1);
                            break;
                        case "全部":
                        default:
                            // 不设置日期范围，查询全部
                            break;
                    }
                }

                // 动态构建查询条件
                if (!string.IsNullOrWhiteSpace(request.RegistrationNum))
                {
                    query = query.Where(pi => pi.RegistrationNum == request.RegistrationNum);
                }

                if (!string.IsNullOrWhiteSpace(request.PatientName))
                {
                    query = query.Where(pi => pi.Patient != null && pi.Patient.PatientName != null && pi.Patient.PatientName.Contains(request.PatientName));
                }

                if (startDate.HasValue)
                {
                    query = query.Where(pi => pi.CreateTime >= startDate.Value);
                }

                if (endDate.HasValue)
                {
                    query = query.Where(pi => pi.CreateTime <= endDate.Value);
                }

                // 按创建时间倒序排列
                var prescriptionItems = await query
                    .OrderByDescending(pi => pi.CreateTime)
                    .ToListAsync(cancellationToken);

                // 获取所有药品列表，用于匹配药品ID
                var allDrugs = await _drugRepo.GetAll()
                    .AsNoTracking()
                    .ToListAsync(cancellationToken);

                // 映射为DTO，并填充患者信息和匹配药品ID
                var dtoList = new List<UnbilledPrescriptionDto>();
                foreach (var item in prescriptionItems)
                {
                    var dto = new UnbilledPrescriptionDto
                    {
                        PrescriptionItemId = item.PrescriptionItemId,
                        AppointmentId = item.AppointmentId,
                        PatientId = item.PatientId,
                        RegistrationNum = item.RegistrationNum,
                        MedicineName = item.MedicineName,
                        UnitPrice = item.UnitPrice,
                        Quantity = item.Quantity,
                        TotalAmount = item.TotalAmount,
                        CreateTime = item.CreateTime,
                        CreateBy = item.CreateBy
                    };

                    // 填充患者信息
                    if (item.Patient != null)
                    {
                        dto.PatientName = item.Patient.PatientName;
                        dto.Gender = item.Patient.Gender;
                        dto.Age = item.Patient.Age;
                        dto.IdCard = item.Patient.IdCard;
                        dto.CardNumber = item.Patient.CardNumber;
                    }

                    // 尝试通过药品名称匹配药品ID
                    if (!string.IsNullOrWhiteSpace(item.MedicineName))
                    {
                        var matchedDrug = allDrugs.FirstOrDefault(d => 
                            d.DrugName != null && 
                            d.DrugName.Equals(item.MedicineName, StringComparison.OrdinalIgnoreCase));
                        if (matchedDrug != null)
                        {
                            dto.DrugId = matchedDrug.DrugId;
                        }
                    }

                    dtoList.Add(dto);
                }

                result.Code = ApiEnum.成功;
                result.Message = "查询成功";
                result.Data = dtoList;
            }
            catch (System.Exception ex)
            {
                result.Code = ApiEnum.失败;
                result.Message = $"查询失败：{ex.Message}";
                result.Data = new List<UnbilledPrescriptionDto>();
            }

            return result;
        }
    }
}




